package org.fglxy.mockserver.controller;


import org.fglxy.mockserver.dto.BaseRespDTO;
import org.fglxy.mockserver.enums.RetCodeEnum;
import org.fglxy.mockserver.exception.MessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ExceptionHandleController {
	
	private static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandleController.class);
	
	/**
	 * 校验错误拦截处理
	 *
	 * @param exception 错误信息集合
	 * @return 错误信息
	 */
	@ExceptionHandler(BindException.class)
	public BaseRespDTO validationBodyException(BindException exception) {
		BindingResult result = exception.getBindingResult();
		if (result.hasErrors()) {
			return new BaseRespDTO(RetCodeEnum.INVALID_PARAM, 
					result.getAllErrors().get(0).getDefaultMessage());
		}
		return null;
	}
	
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public BaseRespDTO validationBodyException(MethodArgumentNotValidException exception) {
		BindingResult result = exception.getBindingResult();
		if (result.hasErrors()) {
			return new BaseRespDTO(RetCodeEnum.INVALID_PARAM, 
					result.getAllErrors().get(0).getDefaultMessage());
		}
		return null;
	}
	
	@ExceptionHandler(MessageException.class)
	public BaseRespDTO messageException(MessageException exception) {
		return new BaseRespDTO(exception.getCode(), exception.getMessage());
	}
	
	@ExceptionHandler(Exception.class)
	public BaseRespDTO defaultException(Exception e) {
		LOGGER.error("error", e);
		return new BaseRespDTO(RetCodeEnum.ERROR);
	}
	
}
